package FilesGenerator

import xml.XML
import xml.PrettyPrinter
import collection.mutable.HashMap

/**
 * Created by IntelliJ IDEA.
 * User: CAPERRITAZ
 * Date: 11.04.11
 * Time: 18:29
 */

import AndroidProjectFile.ProjectParameters

object ManifestFile {

   val dataBase = XML.loadFile("files/permissions.xml")
   val fileName = "AndroidManifest.xml"
   val constPerm = "android.permission."

   def generate(path: String): Unit = {

     var validPerms = List[String]()
     if (!ProjectParameters.permissionList.isEmpty)
         validPerms = getPermission

      val manif = <manifest xmlns:android="http://schemas.android.com/apk/res/android"
	                    package={ProjectParameters.packageName}
	                    android:versionCode={ProjectParameters.versionCode.toInt.toString}
	                    android:versionName={ProjectParameters.versionName}>

         {if (!validPerms.isEmpty)  for (perm <- validPerms) yield
          //@TODO vérifier les guillements sur constPerm
               <uses-permission android:name={constPerm + perm}/>}

   <application android:label="@string/app_name" android:icon="@drawable/icon">
      <activity android:name={ProjectParameters.activityName}
			android:label="@string/app_name">
         <intent-filter>
            <action android:name="android.intent.action.MAIN"></action>
            <category android:name="android.intent.category.LAUNCHER"></category>
         </intent-filter>
      </activity>
   </application>
</manifest>

      XML.save(FileManager.createFile(path, fileName), XML.loadString(new PrettyPrinter(80, 3).format(manif)), "UTF-8", true, null)
   }

   protected def getPermission(): List[String] = {

      var perms = List[String]()

      for (perm <- ProjectParameters.permissionList) {
         for (entry <- dataBase \\ "permission") {
            if ((entry \\ "@name" text) == perm) {
               perms = perms :+ (entry \\ "manifest" text)
            }
         }
      }
      perms
   }

  def getAllPermissions(): HashMap[String,String] = {

      var perms = new HashMap[String, String]()

      for (perm <- ProjectParameters.permissionList) {
         for (entry <- dataBase \\ "permission") {

           perms += ((entry \\ "@name" text) -> (entry \\ "description" text))

         }
      }
      perms
   }
}


